package com.smart.electronic.fence.controller;

import com.alibaba.fastjson.JSONObject;
import com.smart.electronic.fence.pojo.ElectronicFence;
import com.smart.electronic.fence.service.ElectronicFenceService;
import com.smart.electronic.fence.util.QRCodeManageUtil;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping(value = "/fence")
public class ElectronicFenceController {

    @Resource
    private ElectronicFenceService fenceService;

    //缓存文件
    private static final String UPLOADED_FOLDER = System.getProperty("user.dir")+"/upload/img/";



    @PostMapping(value = "/newAdd")
    public JSONObject newAddFenceInfo(@RequestParam  String layerId,
                                      @RequestParam  String coordinates,
                                      @RequestParam  String  fenceName,
                                      @RequestParam   String longitude,
                                      @RequestParam   String latitude,
                                      @RequestParam  String remarks,
                                      @RequestParam("file") MultipartFile file ){
        ElectronicFence fence = new ElectronicFence();
        fence.setLayerId(layerId);
        fence.setCoordinates(coordinates);
        fence.setFenceName(fenceName);
        fence.setLongitude(longitude);
        fence.setLatitude(latitude);
        fence.setRemarks(remarks);
        String filePath = System.getProperty("user.dir");
        try {
            /*
             * 调用工具类生成二维码并输出到输出流中
             */
            String fileName = fence.getLayerId()+".png";
            QRCodeManageUtil.createCodeToFile("https://41a8215d.r5.cpolar.top/mapbox/"+fence.getFenceName(),new File(filePath+"/upload/qrcode"), fileName);
            log.info("成功生成二维码!");
            if (file!=null){
               String fileUrl =  saveFile(file,UPLOADED_FOLDER);
                fence.setFileUrl(fileUrl);
                fenceService.add(fence);
            }

        }catch (Exception e) {
            log.error("发生错误， 错误信息是：{}！", e.getMessage());
        }
        //缓存文件

        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",null);
        return obj;
    }

    public String saveFile(MultipartFile f, String path)throws IOException{
        String fileUrl = null;
        File upDir = new File(path);
        if (!upDir.exists()){
            upDir.mkdir();
        }

        try {
            String filename = f.getOriginalFilename();
            String suffixName = filename.substring(filename.lastIndexOf("."));  // 获取后缀名
            filename = UUID.randomUUID().toString() + suffixName;
            File file = new File(path+ filename);
            f.transferTo(file); // 将MultipartFile类型转为定义好位置的和名字的file
            fileUrl = "/upload/img/"+filename;
        }catch (Exception e){
            e.printStackTrace();
        }
        return fileUrl;
    }
    @RequestMapping("/add")
    public JSONObject addFenceInfo(@RequestBody ElectronicFence fence){
        String filePath = System.getProperty("user.dir");
        try {
            /*
             * 调用工具类生成二维码并输出到输出流中
             */
            String fileName = fence.getLayerId()+".png";
            QRCodeManageUtil.createCodeToFile("https://41a8215d.r5.cpolar.top/mapbox/"+fence.getFenceName(),new File(filePath+"/upload"), fileName);
            log.info("成功生成二维码!");
        }catch (Exception e) {
            log.error("发生错误， 错误信息是：{}！", e.getMessage());
        }
        fenceService.add(fence);
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",null);
        return obj;
    }

    @GetMapping(value = "/remove/{layerId}")
    public  JSONObject removeById(@PathVariable String layerId){
        ElectronicFence fence = fenceService.getById(layerId);
        String filePath = System.getProperty("user.dir");
        File file =new File(filePath+"/upload/qrcode/"+fence.getLayerId()+".png");
        if (file.exists()){
            file.delete();
        }
        File file1 =new File(filePath+fence.getFileUrl());
        if (file1.exists()){
            file1.delete();
        }
        fenceService.removeById(layerId);
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",null);
        return obj;
    }

    @PostMapping(value = "/edit")
    public  JSONObject editBy(@RequestBody ElectronicFence fence){
        fenceService.editById(fence);
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",null);
        return obj;
    }

    @GetMapping(value = "/select_id/{layerId}")
    public  JSONObject getById(@PathVariable String layerId){
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",fenceService.getById(layerId));
        return obj;
    }

    @PostMapping(value = "/select/all")
    public  JSONObject getAll(){
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",fenceService.getAll());
        return obj;
    }
    @GetMapping(value = "/findPage")
    public  JSONObject findPage(Integer pageNum,Integer pageSize){
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",fenceService.findPage(pageNum,pageSize));
        return obj;
    }

    @GetMapping(value = "/seach")
    public  JSONObject seachByPage(String fenceName,Integer pageNum,Integer pageSize){
        JSONObject obj = new JSONObject();
        obj.put("code",200);
        obj.put("data",fenceService.seachByPage(fenceName, pageNum, pageSize));
        return obj;
    }

}
